<template>
  <view class="container">
    <!-- 顶部安全区域占位 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets.top - 10 + 'px' }"></view>

    <!-- 房间成员（折叠面板） -->
    <view v-if="isLoading">
      <uni-collapse>
        <uni-collapse-item title="房间成员" :open="true" :show-arrow="false" :title-border="'none'">
          <view>正在加载房间成员信息...</view>
        </uni-collapse-item>
      </uni-collapse>
    </view>
    <view v-else>
      <uni-collapse>
        <uni-collapse-item title="房间成员" :open="true" :show-arrow="false" :title-border="'none'">
          <view class="content fade-in">
            <view class="user" v-for="(member, userId) in members" :key="userId">
              <image :src="member.avatar" class="avatar"></image>
              <text class="username">{{ member.nickname || member.name }}</text>
            </view>
          </view>
        </uni-collapse-item>
      </uni-collapse>
    </view>

    <!-- 对局记录（消息卡片） -->
    <view class="custom-card" v-for="(record, index) in history" :key="index">
      <view class="card-time">
        <text class="card-text">{{ record.time }} · 第{{ index + 1 }}局</text>
      </view>
      <view class="card-score">
        <view class="card-item" v-for="(score, userId) in record.scores" :key="userId">
          <image 
              :src="members[userId]?.avatar || 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png'" 
              class="avatar"
            ></image>

          <text class="card-text">{{ score["net_gains"] }}</text>
        </view>
      </view>
    </view>

    <!-- 底部功能区域 -->
    <view class="foot fade-in">
      <button class="footbutton-left" @click="handleSettleRound" :disabled="!isConnected">
        <text> 结算本局 </text>
      </button>



	 <button class="share-btn" @click="openShareModal">
	   <image class="share" src="@/static/user.png"></image>
	 </button>

		<!-- 分享模态窗口 -->
		<view class="modal-mask" v-if="showShareModal" @click="closeModal">
		  <view class="modal-container" @click.stop>
		    <view class="modal-header">
		      <text class="modal-title">邀请好友加入</text>
		      <button class="close-btn" @click="closeModal">×</button>
		    </view>
		    
		    <view class="modal-content">
		      <text class="room-id-text">房间ID: {{ roomId }}</text>
		      <view class="qr-code-container">
		        <canvas canvas-id="qrCanvas" class="qr-code" :style="{width: qrSize + 'px', height: qrSize + 'px'}"></canvas>
		      </view>
		      <text class="tip-text">请点击「加入房间」扫描二维码</text>
		    </view>
		    
		    <view class="modal-footer">
		      <button class="cancel-btn" @click="closeModal">取消</button>
	<!-- 	      <button class="confirm-btn" @click="saveQRCode">保存二维码</button> -->
		    </view>
		  </view>
		</view>

	
      

      <button class="footbutton-right" @click="handleLeaveRoom" :disabled="!isConnected">
        离开房间
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useSocketStore } from '@/stores/modules/socketStore.js'; // 引入封装的Socket Store
import drawQrcode from 'weapp-qrcode'


// 获取屏幕尺寸边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
const qrSize = ref(200) // 二维码尺寸

// 使用 Pinia store
const socketStore = useSocketStore();

// 使用 storeToRefs 解构出需要响应式的状态
const { 
  currentMembers: members, // 房间人员
  currentHistory: history,// 对局记录
  currentRoomId: roomId,
  connectionState,
  isConnectedToRoom,
  isConnecting,
  hasError
} = storeToRefs(socketStore);

//******************二维码：模板改了下  加了几个方法  获取了一下尺寸*****************************************************************
const showShareModal = ref(false) // 控制模态窗口显示/隐藏

// 生成二维码（调用weapp-qrcode库）
const generateQRCode = () => {
  drawQrcode({
    canvasId: 'qrCanvas', // 对应canvas的id
    text: roomId.value, // 二维码内容（房间ID）
    width: qrSize.value,
    height: qrSize.value,
    colorDark: '#000000', // 二维码深色
    colorLight: '#ffffff', // 二维码浅色（背景）
    correctLevel: 1 // 纠错等级（1-3，等级越高容错性越强）
  })
}
// 打开分享模态窗口
const openShareModal = () => {
  showShareModal.value = true
  // 延迟生成二维码（确保模态窗口已渲染，避免canvas未加载导致绘制失败）
  setTimeout(() => {
    generateQRCode()
  }, 100)
}

// 关闭模态窗口
const closeModal = () => {
  showShareModal.value = false
}




// 计算属性 - 用于判断折叠面板记载开关是否正在加载
const isLoading = computed(() => {return   Object.keys(members.value).length === 0})
// const isLoading = computed(() => isConnecting.value || !isConnectedToRoom.value(roomId.value));
// const isLoading = ref(false);
const isConnected = computed(() => socketStore.connectionState === 'connected');

// onload:页面首次加载时触发,初始化页面数据或获取传递的参数
// onMounted：Vue 组件挂载到 DOM 后触发,操作 DOM 或初始化依赖 DOM 的逻辑
// 页面加载时获取房间ID并连接
onLoad((options) => {

  
  roomId.value = options.roomId;
  console.log("option：",options)
  console.log("option：",roomId.value)
  if (roomId.value) {
	// 若已连接则复用，未连接则创建（避免重复连接）
	if (!socketStore.isConnectedToRoom(roomId.value)) {
		connectToRoom(); 
		console.log("room页，重新建立WebSocket连接");
	} 
	else {
		console.log("复用已有的WebSocket连接");
	}
  initRoom()
  // socketStore.emit('init_room', { room_id: roomId.value});
  // this.socket.emit('init_room', { room_id: this.currentRoomId});
  } 
  else {
    uni.showToast({ title: '未获取到房间ID', icon: 'none' });
  }
});

const initRoom = async () => {
  try {
	socketStore.emit('init_room', { roomId: roomId.value});
    // 注册Socket事件监听
    register_roompage_SocketListeners();
  } catch (err) {
    error.value = err.message || '加载数据失败，请稍后重试';
    console.error('房间初始化数据出错:', err);
  } 
};

const register_roompage_SocketListeners = () => {};


// 页面显示时执行（从其他页面返回时）
// onShow(() => {
//   // refreshRoomData(); 
// });


// 连接到房间
const connectToRoom = async () => {
  try {
    await socketStore.connect(roomId.value); // 调用Store的连接方法
    console.log('连接房间成功:', roomId.value);
  } catch (err) {
    uni.showToast({ title: '连接失败: ' + err.message, icon: 'none' });
    console.error('连接错误:', err);
  }
};



// 折叠面板数据初始化
// const refreshRoomData = () => {
//   if (!roomId.value) return;
//   isLoading.value = true;
//   socket.value.emit('init_room', { room_id: roomId.value });
// };

// 处理结算本局
const handleSettleRound = async () => {
  try {
    const res = await uni.request({
      url: `http://172.16.24.120:5000/mysqlroom/get_room_info/${roomId.value}`,
      method: 'GET'
    });
    uni.navigateTo({
      url: `/pages/room/roundpay?roomId=${roomId.value}&roundNumber=${res.data.current_game}`
    });
  } catch (err) {
    uni.showToast({ title: '获取房间信息失败', icon: 'none' });
  }
};

// 处理离开房间
const handleLeaveRoom = async () => {
  socketStore.leaveRoom(roomId.value); // 清理房间数据
  socketStore.disconnect(); // 断开连接
  uni.navigateBack();//回到首页
};

// 注册事件监听（组件挂载时）
onMounted(() => {
const systemInfo = uni.getSystemInfoSync();
  qrSize.value = Math.min(systemInfo.windowWidth * 0.6, 300);
  console.log("二维码尺寸：", qrSize.value); // 确认是否为正数（比如200左右）
});

// 移除事件监听（组件卸载时）
onUnmounted(() => {
  socketStore.off('history_update'); // 清理监听
  // 若需要完全断开连接（根据业务场景）
  // if (socketStore.currentRoomId === roomId.value) {
  //   socketStore.disconnect();
  // }
});
</script>

<style>
/* 样式保持不变 */
.navbar {
  /* 安全区域样式 */
}
.container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
.content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
}
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.user {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 13px;
}
.custom-card {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  padding: 20px;
  margin: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  background-color: #fff;
  border-radius: 8px;
}
.card-time {
  margin-bottom: 20px;
}
.card-score {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.card-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 26px;
}
.card-text {
  font-size: 14px;
  color: #a0a6a7;
  text-align: center;
}
.card-item image {
  width: 42px;
  height: 42px;
  margin-bottom: 5px;
  border-radius: 100%;
}
.foot {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.footbutton-left {
  background-color: #8b8a84;
  color: white;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 125px;
  height: 60px;
  font-size: 18px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.footbutton-right {
  background-color: #41403b;
  color: white;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 125px;
  height: 60px;
  font-size: 18px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.share {
  width: 60px;
  height: 60px;
  object-fit: contain;
}
.share:hover {
  transform: scale(1.3);
}
.footbutton-left:hover,
.footbutton-right:hover {
  background-color: #0056b3;
}
.fade-in {
  animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}





/* 二维码 */
/* 动画定义：模态窗口打开时的旋转进入效果 */
@keyframes rotateIn {
  from {
    opacity: 0; /* 初始完全透明 */
    transform: rotate(-20deg) scale(0.5); /* 初始状态：向左旋转20度+缩小到0.5倍 */
  }
  to {
    opacity: 1; /* 结束时完全显示 */
    transform: rotate(0deg) scale(1); /* 结束状态：正常角度+正常大小 */
  }
}

.room-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh; /* 占满整个屏幕高度 */
}

.room-info {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05); /* 轻微阴影 */
}

.room-id {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 24rpx;
  display: block; /* 独占一行 */
}

.share-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 240rpx;
  height: 80rpx;
  margin: 20rpx auto 40rpx;
  background-color: #409EFF;
  color: white;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
  
  image {
    width: 36rpx;
    height: 36rpx;
    margin-right: 10rpx;
  }
}

.members-list {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
}

.section-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
  display: block;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #eee;
  
  &:last-child {
    border-bottom: none; /* 最后一个成员取消下边框 */
  }
  
  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%; /* 圆形头像 */
    margin-right: 20rpx;
  }
}

/* 模态窗口样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000; /* 确保在最上层 */
}

.modal-container {
  width: 80%;
  max-width: 600rpx;
  background-color: white;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
  /* 应用旋转进入动画 */
  animation: rotateIn 0.4s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  background-color: #f5f5f5;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 44rpx;
  color: #999;
  background: transparent;
  border: none;
  padding: 0;
  line-height: 1;
}

.modal-content {
  padding: 40rpx 32rpx;
  text-align: center;
  
  .room-id-text {
    font-size: 30rpx;
    color: #409EFF; /* 突出显示房间ID */
    margin-bottom: 30rpx;
    display: block;
  }
  
  .tip-text {
    font-size: 26rpx;
    color: #888;
    margin-top: 30rpx;
    display: block;
  }
}

.qr-code-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30rpx auto;
  padding: 20rpx;
  background-color: #fff;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
}

.qr-code {
  display: block;
  
}

.modal-footer {
  display: flex;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
  
  button {
    flex: 1; /* 两个按钮平分宽度 */
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 10rpx;
    font-size: 30rpx;
    margin: 0 10rpx;
    border: none;
    
    &.cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }
    
    &.confirm-btn {
      background-color: #409EFF;
      color: white;
    }
  }
}
</style>